
import os
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.contrib import messages
from projsettings.settings import app_settings
from computes.models import Compute
from libvirtmgr.storage import wvmStorage
from django.http import HttpResponseRedirect
from django.utils.translation import gettext_lazy as _

# Create your views here.

def storage_pool_index(request):
    compute_id = app_settings.STORAGE_COMPUTE_ID
    pool = app_settings.STORAGE_POOL_NAME
    
    compute = get_object_or_404(Compute, pk=compute_id)
    
    conn = wvmStorage(
        compute.hostname, compute.login, compute.password, compute.type, pool
    )
    
    state = conn.is_active()
    size, free = conn.get_size()
    used = size - free
    if state:
        percent = (used * 100) // size
    else:
        percent = 0
    status = conn.get_status()
    path = conn.get_target_path()
    type = conn.get_type()
    autostart = conn.get_autostart()

    if state:
        conn.refresh()
        volumes = conn.update_volumes()
    else:
        volumes = None
    
    if request.method == "POST":
        if "start" in request.POST:
            conn.start()
            return HttpResponseRedirect(request.get_full_path())
        if "stop" in request.POST:
            conn.stop()
            return HttpResponseRedirect(request.get_full_path())
        if "delete" in request.POST:
            conn.delete()
            return HttpResponseRedirect(reverse("storages", args=[compute_id]))
        if "set_autostart" in request.POST:
            conn.set_autostart(1)
            return HttpResponseRedirect(request.get_full_path())
        if "unset_autostart" in request.POST:
            conn.set_autostart(0)
            return HttpResponseRedirect(request.get_full_path())
        if "del_volume" in request.POST:
            volname = request.POST.get("volname", "")
            vol = conn.get_volume(volname)
            vol.delete(0)
            messages.success(
                request, _("Volume: %(vol)s is deleted.") % {"vol": volname}
            )
            return redirect(reverse("storage", args=[compute.id, pool]))
    
    return render(
        request,
        'storage_pool_index.html',
        locals()
    )
    
    
def images_pool_index(request):
    
    def handle_uploaded_file(path, f_name):
        target = os.path.normpath(os.path.join(path, str(f_name)))
        if not target.startswith(path):
            raise Exception(_("Security Issues with file uploading"))

        try:
            with open(target, "wb+") as f:
                for chunk in f_name.chunks():
                    f.write(chunk)
        except FileNotFoundError:
            messages.error(
                request, _("File not found. Check the path variable and filename")
            )
            
    compute_id = app_settings.STORAGE_COMPUTE_ID
    pool = app_settings.ISO_STORAGE_NAME
    
    compute = get_object_or_404(Compute, pk=compute_id)
    
    conn = wvmStorage(
        compute.hostname, compute.login, compute.password, compute.type, pool
    )
    
    state = conn.is_active()
    size, free = conn.get_size()
    used = size - free
    if state:
        percent = (used * 100) // size
    else:
        percent = 0
    status = conn.get_status()
    path = conn.get_target_path()
    type = conn.get_type()
    autostart = conn.get_autostart()

    if state:
        conn.refresh()
        volumes = conn.update_volumes()
    else:
        volumes = None
        
    if request.method == "POST":
        if "start" in request.POST:
            conn.start()
            return HttpResponseRedirect(request.get_full_path())
        if "stop" in request.POST:
            conn.stop()
            return HttpResponseRedirect(request.get_full_path())
        if "delete" in request.POST:
            conn.delete()
            return HttpResponseRedirect(reverse("storages", args=[compute_id]))
        if "set_autostart" in request.POST:
            conn.set_autostart(1)
            return HttpResponseRedirect(request.get_full_path())
        if "unset_autostart" in request.POST:
            conn.set_autostart(0)
            return HttpResponseRedirect(request.get_full_path())
        if "del_volume" in request.POST:
            volname = request.POST.get("volname", "")
            vol = conn.get_volume(volname)
            vol.delete(0)
            messages.success(
                request, _("Volume: %(vol)s is deleted.") % {"vol": volname}
            )
            return redirect(reverse("storage", args=[compute.id, pool]))
            # return HttpResponseRedirect(request.get_full_path())
        if "iso_upload" in request.POST:
            if str(request.FILES["file"]) in conn.update_volumes():
                error_msg = _("ISO image already exist")
                messages.error(request, error_msg)
            else:
                handle_uploaded_file(path, request.FILES["file"])
                messages.success(
                    request,
                    _("ISO: %(file)s is uploaded.") % {"file": request.FILES["file"]},
                )
                return HttpResponseRedirect(request.get_full_path())
    
    return render(
        request,
        'images_pool_index.html',
        locals()
    )